<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\User\CreateTeacher;
use App\Http\Requests\User\EmailRequest;
use App\Repositories\Cache\RegisterCode;
use App\Models\User;
use Illuminate\Support\Facades\Mail;

/**
 * 注册控制器
 *
 * Class RegisterController
 * @package App\Http\Controllers\Api
 */
class RegisterController extends Controller
{
    /**
     * user register and send verification email
     *
     * @param CreateTeacher $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(CreateTeacher $request)
    {
        $name = $request->input('name');
        $password = $request->input('password');
        $email = $request->input('email');
        $code = $request->input('code');
        // 查询缓存中的验证码并进行验证
        $registerCode = new RegisterCode();
        $cacheCode = $registerCode->getCode($email);
        if (! $cacheCode) {
            return error("Please click to send email verification code");
        }
        if ($cacheCode != $code) {
            return error("verification failed");
        }

        // 创建用户
        $userData = [
            'name' => $name,
            'password' => bcrypt($password),
            'email' => $email,
        ];
        User::create($userData);

        return success();
    }

    /**
     * send verification email
     *
     * @param EmailRequest $request
     *
     * @return \Illuminate\Http\JsonResponse
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function sendRegEmail(EmailRequest $request)
    {
        $email = $request->input('email');
        $ip = $request->getClientIp();

        // 检测邮件发送次数是否超限
        $registerCode = new RegisterCode();
        if (! $registerCode->check($email) || ! $registerCode->check($ip)) {
            return error("overrun times");
        }

        // 生成验证码缓存
        $code = rand6();
        $registerCode->setCodeCache($email, $code);
        $registerCode->setSendTimesCache($email);
        $registerCode->setSendTimesCache($ip);

        // 发送邮件
        $subject = 'Welcome to Educational! Confirm Your Email';
        Mail::send(
            'emails.manager-verification',
            ['code' => $code],
            function ($message) use ($email, $subject) {
                $message->to($email)->subject($subject);
            }
        );

        return success();
    }

}